package simi;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RecentImageServlet extends HttpServlet {

	/**
	 * Need a UID to extend HttpServlet
	 */
	private static final long serialVersionUID = 1L;

	// To-do: use a hash here
	private static String[] imageTypes = SimiPropertyManager.getConfig()
			.getStringArray("images.type");
	private static String[] mimeTypes = SimiPropertyManager.getConfig()
			.getStringArray("images.mime");

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

		File lastModifiedImageFile = (File) req.getSession().getAttribute(
				"recentImageFile");

		if (lastModifiedImageFile != null) {
			byte[] imageBytes = getRawBytes(lastModifiedImageFile);
			res.setContentType(getMimeTypeForImage(lastModifiedImageFile
					.getName().toLowerCase()));

			res.setHeader("Content-Disposition", "inline; filename="
					+ lastModifiedImageFile.getName());
			res.setStatus(HttpServletResponse.SC_OK);

			res.setHeader("Cache-Control", "no-store"); // HTTP 1.1
			res.setHeader("Pragma", "no-cache"); // HTTP 1.0
			res.setDateHeader("Expires", 0); // prevents caching at the proxy
												// server

			ServletOutputStream out = res.getOutputStream();
			out.write(imageBytes);
			out.flush();
			out.close();
		} else {
			res.setContentType("text/plain");
			res.setHeader("Cache-Control", "no-cache");
			PrintWriter pw = res.getWriter();
			pw.write("No image...");
			pw.close();
		}
	}

	private final static byte[] getRawBytes(File f) {

		try {
			FileInputStream fin = new FileInputStream(f);
			byte[] buffer = new byte[(int) f.length()];
			fin.read(buffer);
			fin.close();
			return buffer;
		} catch (Exception err) {
			err.printStackTrace();
		}
		return null;
	}

	private static String getMimeTypeForImage(String fileName) {
		String theMime = null;
		String ext = SimiUtils.getFileExtension(fileName).toLowerCase();

		// To-do: use a hash here
		if (ext != null && imageTypes != null) {
			for (int i = 0; i < imageTypes.length; i++) {
				String testExt = imageTypes[i].toLowerCase();
				if (ext.equals(testExt)) {
					theMime = mimeTypes[i];
					break;
				}
			}
		}

		return theMime;
	}
}
